package com.treasure.web.controller.test;

import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.treasure.common.utils.TSON;
import com.treasure.infrastructure.client.SseEmitterServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SSE 服务端
 * @author sunhongmin
 * @date 2023/9/13 23:19
 * @description SseEmitterServer
 */
@RestController
@RequestMapping("/treasure/test/sse")
@Slf4j
@Deprecated
public class SseEmitterController {

    /**
     * 用于创建连接
     */
    @GetMapping("/connect/{userId}/{message}")
    public SseEmitter connect(@PathVariable String userId, @PathVariable String message) throws NoApiKeyException, InputRequiredException, InterruptedException {
        SseEmitter connect = SseEmitterServer.connect(userId);
        QwenClient.streamCallWithMessageCallback(message, new ResultCallback<GenerationResult>() {
            @Override
            public void onEvent(GenerationResult generationResult) {
                String content = generationResult.getOutput().getChoices().get(0).getMessage().getContent();
                log.info("generationResult:{}", content);
                Map<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("data", content);
                SseEmitterServer.sendMessage(userId, TSON.toJsonString(hashMap));
            }

            @Override
            public void onComplete() {
                Map<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("data", "SSE-END");
                SseEmitterServer.sendMessage(userId, TSON.toJsonString(hashMap));
            }

            @Override
            public void onError(Exception e) {
                Map<String, String> hashMap = new HashMap<String, String>();
                hashMap.put("data", "SSE-END-ERROR");
                SseEmitterServer.sendMessage(userId, TSON.toJsonString(hashMap));
                SseEmitterServer.removeUser(userId);
            }
        });
        return connect;
    }

    /**
     * 关闭连接
     * @param userId
     */
    @GetMapping("/close/{userId}")
    public void close(@PathVariable String userId) {
        SseEmitterServer.removeUser(userId);
    }

    /**
     * 获取当前在线用户
     * @return
     */
    @GetMapping("/list")
    public ResponseEntity<List<String>> list() {
        return ResponseEntity.ok(SseEmitterServer.getIds());
    }

    /**
     * 获取当前在线人数
     * @return
     */
    @GetMapping("/count")
    public ResponseEntity<Integer> getUserCount() {
        return ResponseEntity.ok(SseEmitterServer.getUserCount());
    }

    /**
     * 推送消息给所有人
     * @param message
     * @return
     */
    @GetMapping("/push/{message}")
    public ResponseEntity<String> push(@PathVariable(name = "message") String message) {
        SseEmitterServer.batchSendMessage(message);
        return ResponseEntity.ok("SseEmitter 推送消息给所有人");
    }

    /**
     * 推送消息给指定用户
     * @param userId
     * @param message
     * @return
     */
    @GetMapping("/pushTag/{userId}/{message}")
    public ResponseEntity<String> pushTag(@PathVariable(name = "userId") String userId,
                                          @PathVariable(name = "message") String message) {
        SseEmitterServer.sendMessage(userId, message);
        return ResponseEntity.ok("SseEmitter 推送消息给：" + userId);
    }
}
